﻿using NLog;
using System.Reflection;
using System.Windows;
using System;
using System.IO;
using System.Threading;

namespace Com.Lancetinc.Evs;

public static class Program
{
    public static uint SingleInstanceMsgId;
    private static Mutex _mutex;
    private static App _app;

    [STAThread]
    public static void Main(string[] args)
    {
        var logger = LogManager.GetCurrentClassLogger();
        logger.Info($"\n\n\napp startup,V{AppConsts.InnerAppVersion}, F{GetAppFileModifyTime()}...");

        try
        {
            if (!BeforeStartup())
                return;

            new SplashScreenWin().Show();

            _app = new App();
            _app.Run();
        }
        catch (Exception ae)
        {
            logger.Error(ae.ToString());
            var exeFilename = Path.GetFileName(Assembly.GetEntryAssembly().Location);
            MessageBox.Show(ae.Message, exeFilename, MessageBoxButton.OK, MessageBoxImage.Error);
        }
        finally
        {
            _mutex.ReleaseMutex();
            _mutex.Dispose();
        }
    }

    private static bool BeforeStartup()
    {
        var mutexName = AppConsts.AppUniqueId;

        _mutex = new Mutex(true, mutexName, out var mutexCreated);
        SingleInstanceMsgId = NativeMethods.RegisterWindowMessage(mutexName);

        if (!mutexCreated)
        {
            _mutex = null;

            NativeMethods.PostMessage((IntPtr)NativeMethods.HWND_BROADCAST, (int)SingleInstanceMsgId, IntPtr.Zero,
                IntPtr.Zero);

            return false;
        }

        return true;
    }

    private static string GetAppFileModifyTime()
    {
        var exeFilename = Path.GetFileName(Assembly.GetExecutingAssembly().Location);
        return new FileInfo(exeFilename).LastWriteTime.ToString("yyyy-MM-dd HH:mm:ss");
    }
}